package com.cbgolf.oa.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.cbgolf.oa.R;
import com.cbgolf.oa.app.AppManager;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DensityUtil;
import com.cbgolf.oa.util.PopUtil;
import com.cbgolf.oa.util.ScreenUtil;
import com.cbgolf.oa.util.StatusBarUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.widget.autolayout.AutoLayoutActivity;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import io.reactivex.functions.Consumer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Created by lq on 2018/3/27.
 */

public abstract class BaseNewActivity extends AutoLayoutActivity {

  protected BaseNewActivity context;


  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    context = this;
    if (translucentStatusBar()) {
      setStatusBarTranslucent();
    }
    AppManager.getNewInstance().addActivity(this);
    beforeInit();
    if (getLayoutId() != 0) {
      setContentView(getLayoutId());
      setStatusBar();
      AutoUtil.auto(this);
      init(savedInstanceState);
      setViews();
      setListener();
    }
  }

  protected void setStatusBar() {

  }

  @Override
  protected void onDestroy() {
    AnimaUtil.stopLoading();
    PopUtil.release();
    AppManager.getNewInstance().removeActivity(this);
    super.onDestroy();
  }

  protected void setViews() {

  }

  protected void setListener() {

  }

  /**
   * 界面初始化前期准备
   */
  protected void beforeInit() {

  }

  protected abstract int getLayoutId();

  protected abstract void init(Bundle savedInstanceState);

  /**
   * 子类可以重写改变状态栏颜色
   */
  protected void setStatusBarTranslucent() {
    StatusBarUtil.setStatusBarTranslucent(this, isLightStatusBar());
  }

  /**
   * 子类可以重写决定是否使用透明状态栏
   */
  protected boolean translucentStatusBar() {
    return true;
  }

  protected boolean isLightStatusBar() {
    return true;
  }

  protected void mStartActivity(Class c) {
    mStartActivity(c, null);
  }

  protected void mStartActivity(Class c, String key, String value) {
    Map<String, String> map = new HashMap<>();
    map.put(key, value);
    mStartActivity(c, map);
  }

  protected void mStartActivity(Class c, Map<String, String> map) {
    Intent intent = new Intent(context, c);
    if (null != map && !map.isEmpty()) {
      Set<Map.Entry<String, String>> set = map.entrySet();
      for (Map.Entry<String, String> me : set) {
        intent.putExtra(me.getKey(), me.getValue());
      }
    }
    startActivity(intent);
    overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
  }

  protected void mStartActivity(Intent intent) {
    if (null == intent) {
      return;
    }
    startActivity(intent);
    overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
  }

  @Override
  public void finish() {
    super.finish();
    overridePendingTransition(R.anim.in_from_left, R.anim.out_from_right);
//        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
      onKeyBack();
      return true;
    } else if (keyCode == KeyEvent.KEYCODE_MENU) {

    } else if (keyCode == KeyEvent.KEYCODE_HOME) {
      moveTaskToBack(true);
      return true;
    }
    return super.onKeyDown(keyCode, event);
  }

  protected void onKeyBack() {
    finish();
  }

  protected void requestPermission(List<String> list) {
    if (Util.listIsNull(list)) {
      return;
    }
    permissions = new String[list.size()];
    for (int i = 0; i < list.size(); i++) {
      permissions[i] = list.get(i);
    }
    requestPermission(permissions);
  }

  protected void requestPermission(String[] permissions) {
    RxPermissions rxPermission = new RxPermissions(this);
    rxPermission.requestEach(permissions)
        .subscribe(new Consumer<Permission>() {
          @Override
          public void accept(Permission permission) throws Exception {
            if (permission.granted) {
              // 用户已经同意该权限
              getPermissionSuccess();
            } else if (permission.shouldShowRequestPermissionRationale) {
              // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
//              showSettingDialog();
              getPermissionFail();
            } else {
              // 用户拒绝了该权限，并且选中『不再询问』
//              showSettingDialog();
              getPermissionFail();
            }
          }
        });
  }

  protected void getPermissionFail() {
  }

  private Dialog settingDialog;

  protected void showSettingDialog(List<String> listPermissionNames, IPermissionWaiter waiter) {
    settingDialog = new Dialog(context, R.style.mDialog);
    View view = getLayoutInflater().inflate(R.layout.dialog_modify, null);
    View layout = view.findViewById(R.id.dialog_modify_layout_ll);
    LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams) layout.getLayoutParams();
    ll.width = (int) (ScreenUtil.getWidth() - getResources().getDimension(R.dimen.px116));
    ll.height = LayoutParams.WRAP_CONTENT;
    layout.setLayoutParams(ll);
    TextView titleTv = view.findViewById(R.id.dialog_modify_title_tv);
    TextView contentTv = view.findViewById(R.id.dialog_modify_content_tv);
    TextView sureTv = view.findViewById(R.id.dialog_modify_sure_tv);
    TextView cancelTv = view.findViewById(R.id.dialog_modify_cancel_tv);
    TextView listTv = view.findViewById(R.id.dialog_modify_list_tv);
    AutoUtil.auto(view);
    settingDialog.setContentView(view);
    titleTv.setText("权限不可用");
//    List<String> list = PermissionUtils.getLocationPermissionNames();
    String pNames = null;
    if (!Util.listIsNull(listPermissionNames)) {
      StringBuilder sb = new StringBuilder();
      for (String s : listPermissionNames) {
        sb.append(s).append("、");
      }
      if (!Util.isNull(sb.toString()) && sb.toString().endsWith("、")) {
        pNames = sb.toString().substring(0, sb.toString().length() - 1);
      }
    }
    contentTv.setText("当前缺少必要权限，可能导致部分功能暂时无法使用。如若需要，请单击【去设置】按钮前往设置中心进行权限授权。");
    if (!Util.isNull(pNames)) {
      listTv.setText(pNames);
    }
    sureTv.setText("去设置");
    cancelTv.setText("稍后再说");
    sureTv.setOnClickListener(v -> {
      settingDialog.cancel();
      settingDialog.dismiss();
      goToAppSetting();
    });
    cancelTv.setOnClickListener(v -> {
      settingDialog.cancel();
      settingDialog.dismiss();
      if (null != waiter) {
        waiter.doCancel();
      }
    });
    settingDialog.setCancelable(false);
    settingDialog.show();
  }

  private int REQUEST_CODE_PERMISSION = 0x00099;

  // 跳转到当前应用的设置界面
  private void goToAppSetting() {
    try {
      Intent intent = new Intent();
      intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
      Uri uri = Uri.fromParts("package", getPackageName(), null);
      intent.setData(uri);
      startActivityForResult(intent, REQUEST_CODE_PERMISSION);
      overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
    } catch (Exception e) {

    }
  }
//
//  @Override
//  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//    super.onActivityResult(requestCode, resultCode, data);
//    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//      // 检查该权限是否已经获取
//      int i = ContextCompat.checkSelfPermission(this, permissions[0]);
//      // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
//      if (i == PackageManager.PERMISSION_GRANTED) {
//        getPermissionSuccess();
//      }
//    }
//  }

  protected void getPermissionSuccess() {

  }

  protected String[] permissions;

  // 提示用户该请求权限的弹出框
  protected void showPermissionDialog(final List<String> listPer, List<String> perNames) {
    if (Util.listIsNull(listPer)) {
      return;
    }
    permissions = new String[listPer.size()];
    for (int i = 0; i < listPer.size(); i++) {
      permissions[i] = listPer.get(i);
    }
    final Dialog dialog = new Dialog(context, R.style.mDialog);
    dialog.setContentView(R.layout.dialog_modify);
    View layout = dialog.findViewById(R.id.dialog_modify_layout_ll);
    LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams) layout.getLayoutParams();
    ll.width = getWindowManager().getDefaultDisplay().getWidth() - DensityUtil
        .dip2px(context, 58);
    ll.height = LayoutParams.WRAP_CONTENT;
    layout.setLayoutParams(ll);
    TextView titileTv = dialog.findViewById(R.id.dialog_modify_title_tv);
    TextView contentTv = dialog.findViewById(R.id.dialog_modify_content_tv);
    TextView sureTv = dialog.findViewById(R.id.dialog_modify_sure_tv);
    TextView cancelTv = dialog.findViewById(R.id.dialog_modify_cancel_tv);
    TextView listTv = dialog.findViewById(R.id.dialog_modify_list_tv);
    String pNames = null;
    if (!Util.listIsNull(perNames)) {
      StringBuilder sb = new StringBuilder();
      for (String s : perNames) {
        sb.append(s).append("、");
      }
      if (!Util.isNull(sb.toString()) && sb.toString().endsWith("、")) {
        pNames = sb.toString().substring(0, sb.toString().length() - 1);
      }
    }
    titileTv.setText("权限不可用");
    contentTv.setText("当前缺少必要功能权限，部分功能无法正常使用！请开启以下权限:");
    if (!Util.isNull(pNames)) {
      listTv.setText(pNames);
    }
    sureTv.setText("立即开启");
    cancelTv.setText("稍后再说");
    sureTv.setOnClickListener(v -> {
      dialog.cancel();
      dialog.dismiss();
      requestPermission(permissions);
    });
    cancelTv.setOnClickListener(v -> {
      dialog.cancel();
      dialog.dismiss();
    });
    dialog.setCancelable(false);
    dialog.show();
  }

  public interface IPermissionWaiter {

//    void doSubmit();

    void doCancel();
  }
}
